package com.ybt.heartratem.moudle;

import android.app.Application;
import android.content.Context;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ybt.heartratem.R;
import com.ybt.heartratem.common.app.AppController;
import com.ybt.heartratem.common.app.CacheManager;
import com.ybt.heartratem.common.entity.ClassInfo;
import com.ybt.heartratem.common.entity.CookBookInfo;
import com.ybt.heartratem.common.entity.SchoolInfo;
import com.ybt.heartratem.common.entity.TeacherInfo;
import com.ybt.heartratem.common.utils.FileUtil;
import com.ybt.heartratem.logic.data.http.service.entry.AASRequestBody;
import com.ybt.heartratem.logic.data.repositor.AASDataRepository;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.http.ApiDisposableObserver;
import me.goldze.mvvmhabit.http.BaseResponse;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.ToastStatusUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import okhttp3.ResponseBody;

/***
 * 主页视图model
 */
public class MainVM extends BaseViewModel<AASDataRepository> {
    public SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    public ObservableField<String> currentDate = new ObservableField<>();
    public SingleLiveEvent<List<CookBookInfo>> getCookBookEvent = new SingleLiveEvent<>();
    public SingleLiveEvent<Boolean> getSaveLiuyangResultEvent = new SingleLiveEvent<>();
    public ObservableField<AASRequestBody> reqBody = new ObservableField<>();
    public Context mContext;

    public void setContext(Context mContext) {
        this.mContext = mContext;
    }

    public MainVM(@NonNull Application application, AASDataRepository aasDataRepository) {
        super(application, aasDataRepository);
        currentDate.set(dateFormat.format(new Date()));
    }

    public void getSchoolData(int SchoolID) {
        addSubscribe(model.getSchoolInfo(SchoolID)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new ApiDisposableObserver() {
                    @Override
                    public void onResult(Object o) {
                        SchoolInfo schoolInfo = new Gson().fromJson(o.toString(), SchoolInfo.class);
                        if (schoolInfo != null) {
                            model.saveUserName(String.valueOf(SchoolID));
                            model.saveToken(schoolInfo.getName());
                            startActivity(MainActivity.class);
                            finish();
                        } else {
                            ToastStatusUtils.show("学校信息不存在", R.drawable.ic_error);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                }));
    }

    /***
     * 根据学校ID获取厨师信息
     */
    public SingleLiveEvent<List<TeacherInfo>> getTeacherListEvent = new SingleLiveEvent<>();

    public void getTeacherList() {
        addSubscribe(model.GetEmployeeList(model.getUserName(), 17)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new ApiDisposableObserver() {
                    @Override
                    public void onResult(Object o) {
                        BaseResponse baseResponse = (BaseResponse) o;
                        if (baseResponse != null) {
                            List<TeacherInfo> list = (List<TeacherInfo>) baseResponse.getData();
                            if (list != null && !list.isEmpty()) {
                                getTeacherListEvent.setValue(list);
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                }));
    }

    public SingleLiveEvent<List<ClassInfo>> getClaInfoListEvent = new SingleLiveEvent<>();

    public void loadClassData() {
        addSubscribe(model.getClassList(model.getUserName())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new ApiDisposableObserver() {
                    @Override
                    public void onResult(Object o) {
                        BaseResponse baseResponse = (BaseResponse) o;
                        if (baseResponse != null) {
                            List<ClassInfo> list = (List<ClassInfo>) baseResponse.getData();
                            if (list != null && !list.isEmpty()) {
                                getClaInfoListEvent.setValue(list);
                            }
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                }));
    }

    /***
     * 获取食谱
     * @param typeOf
     * @param DateFrom
     * @param DateTo
     */
    public void getFoodList(String typeOf, String DateFrom, String DateTo) {
        addSubscribe(model.getFoodBook(model.getUserName(), typeOf, DateFrom, DateTo)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new ApiDisposableObserver() {
                    @Override
                    public void onResult(Object o) {
                        List<CookBookInfo> list = new Gson().fromJson(o.toString(), new TypeToken<List<CookBookInfo>>() {
                        }.getType());
                        getCookBookEvent.setValue(list);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                }));
    }

    public void addRecord() {
        addSubscribe(model.AddRecord(reqBody.get())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new ApiDisposableObserver() {
                    @Override
                    public void onResult(Object o) {
                        try {
                            String result = ((ResponseBody) o).string();
                            if (result.contains("OK")) {
                                ToastStatusUtils.show("提交留样数据保存成功", R.drawable.ic_req_success);
                                getSaveLiuyangResultEvent.setValue(true);
                            } else {
                                ToastStatusUtils.show("添加留样数据失败，错误原因：" + result, R.drawable.ic_error);
                                getSaveLiuyangResultEvent.setValue(false);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                }));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
